import React, { useState, useEffect, FC, SyntheticEvent, ChangeEvent, useRef, MutableRefObject } from 'react'
import {
  Space, Row, Col, Input,
  Form, Table, Modal, Card, InputNumber
} from 'antd'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import DictValueXlModalFC, { IDictValueRef } from './components/dictvaluemodal/dictvaluemodal'
import { Scrollbars } from 'react-custom-scrollbars'
import * as api from '@/api'
import { IData, PagingSize, DictionaryTypeModal, IResponseCodeType } from '@/models/common'
import { DownOutlinedIcon } from '@/models/icons'
import util from '@/utils/util'
import './dictsetting.scss'
interface ColumnsDataType {
  [name: string]: string
}
export interface IViewModel {
  dictUpdateModalOpen: boolean
  /**
   * 当前修改行信息
   */
  dictUpdateRow: ColumnsDataType
  pageLoading: boolean
  /**
   * 表格数据
   */
  dictTableList: ColumnsDataType[]
  /**
  * 当前页码
  */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean
  notAuth: boolean
}

const Index: FC = () => {
  const dictValueRef: MutableRefObject<IDictValueRef> = useRef({
    getValue: (type_id: string) => { }
  })
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      dictUpdateModalOpen: false,
      dictUpdateRow: {
        id: "",
        type_label: "",
        order_sort: ""
      },
      pageLoading: false,
      dictTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])

  const events = {
    onClickAddRow() {
      const { ViewModel } = data
      ViewModel.dictUpdateRow.type_label = ''
      ViewModel.dictUpdateRow.id = ''
      ViewModel.dictUpdateRow.order_sort = ''
      ViewModel.dictUpdateModalOpen = true
      setData({ ...data })
    },
    //编辑
    onClickEditRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.dictUpdateRow.type_label = record.type_label
      ViewModel.dictUpdateRow.id = record.id
      ViewModel.dictUpdateRow.order_sort = record.order_sort
      ViewModel.dictUpdateModalOpen = true
      setData({ ...data })
    },
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteDictionaryType(record.id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickSetValueRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      dictValueRef.current.getValue(record.id)
    },
    onDictUpdateTypeNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.dictUpdateRow.type_label = e.target.value
      setData({ ...data })
    },
    onDictUpdateOrderSortChange(value: number | string | null) {
      const { ViewModel } = data
      ViewModel.dictUpdateRow.order_sort = value as string
      setData({ ...data })
    },
    onDictUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.dictUpdateRow.type_label) {
        util.alertTip('请输入数据字典名称')
        return
      }
      if (ViewModel.dictUpdateRow.id) {
        methods.requestUpdateDictionaryType()
      } else {
        methods.requestAddDictionaryType()
      }
    },
    onDictUpdateRowCancel() {
      const { ViewModel } = data
      ViewModel.dictUpdateRow.type_label = ''
      ViewModel.dictUpdateRow.id = ''
      ViewModel.dictUpdateModalOpen = false
      setData({ ...data })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        // ViewModel.page = ViewModel.page + 1
        // ViewModel.pageLoading = true
        // setData({ ...data })
        // methods.querySubTableList()
      }
    },
  }
  const methods = {
    /**
     * 加载字典
     */
    async requestDictionaryTypeList() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getDictionaryTypeList<DictionaryTypeModal>(null)
      const { code, data: DictionaryTypeData, message } = res
      if (code == IResponseCodeType.Success) {
        let { type_list = [] } = DictionaryTypeData
        ViewModel.dictTableList = [...type_list]
        if (type_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = false
        }
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 新增字典
     */
    async requestAddDictionaryType() {
      const { ViewModel } = data
      let res = await api.common.addDictionaryType({
        type_label: ViewModel.dictUpdateRow.type_label,
        order_sort: ViewModel.dictUpdateRow.order_sort
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.dictUpdateRow.type_label = ''
        ViewModel.dictUpdateRow.id = ''
        ViewModel.dictUpdateRow.order_sort = ''
        ViewModel.dictUpdateModalOpen = false
        setData({ ...data })
        methods.requestDictionaryTypeList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 更新字典
     */
    async requestUpdateDictionaryType() {
      const { ViewModel } = data
      let res = await api.common.updateDictionaryType({
        type_label: ViewModel.dictUpdateRow.type_label,
        id: ViewModel.dictUpdateRow.id,
        order_sort: ViewModel.dictUpdateRow.order_sort
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.dictUpdateRow.type_label = ''
        ViewModel.dictUpdateRow.id = ''
        ViewModel.dictUpdateRow.order_sort = ''
        ViewModel.dictUpdateModalOpen = false
        setData({ ...data })
        methods.requestDictionaryTypeList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除字典
     * @param id 
     */
    async requestDeleteDictionaryType(id: string) {
      let res = await api.common.deleteDictionaryType<null>({
        id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        methods.requestDictionaryTypeList()
      } else {
        util.alertTip(message)
      }
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '排序号',
          align: "left",
          key: 'order_sort',
          dataIndex: 'order_sort',
        },
        {
          title: '数据字典名称',
          align: "left",
          key: 'type_label',
          dataIndex: 'type_label',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickEditRow(_, record, index)}>
                修改
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
                删除
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickSetValueRow(_, record, index)}>
                设置值
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Card title="数据字典管理">
          <Col className='dict-setting-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={6}>
                  <XlButtonFC type='primary' onClick={events.onClickAddRow}>新增</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.dictTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Row className='tableWrap'>
              <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                <Table
                  scroll={{
                    x: '100%',
                    y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                  }}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  rowKey='id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.dictTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Row>
          </Col>
        </Card>
        {/* 添加修改弹出框 */}
        <XlModalFC
          open={data.ViewModel.dictUpdateModalOpen}
          onOk={events.onDictUpdateRowOk}
          onCancel={events.onDictUpdateRowCancel}
          title='新增/修改'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 16 }}
            autoComplete="off"
          >
            <Form.Item
              label="数据字典名称"
              required
            >
              <Input value={data.ViewModel.dictUpdateRow.type_label} onChange={events.onDictUpdateTypeNameChange} allowClear placeholder='请输入数据字典名称' />
            </Form.Item>
            <Form.Item
              label="排序号"
            >
              <InputNumber value={data.ViewModel.dictUpdateRow.order_sort} onChange={events.onDictUpdateOrderSortChange} placeholder='请输入排序号' style={{ width: "100%" }} />
            </Form.Item>
          </Form>
        </XlModalFC>
        <DictValueXlModalFC
          ref={dictValueRef}
        />
      </>
    }
  }
  return methods.renderPage()
}
export default Index
